package com.borrow.jiemihua.mainUI.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseActivity;
import com.borrow.jiemihua.base.BaseApplication;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.mainUI.activity.LoginRegister.LoginActivity;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.borrow.jiemihua.view.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cc.duduhuo.custoast.CusToast;

@ContentView(R.layout.activity_personal_data)
public class PersonalDataActivity extends BaseActivity {
    @ViewInject(R.id.tv_top_title)
    private TextView tv_top_title;
    @ViewInject(R.id.head_image)
    private CircleImageView head_image;
    @ViewInject(R.id.tv_nick)
    private TextView tv_nick;
    private Bitmap head_btm;//头像Bitmap
    private String headPath;
    private static String path = "/sdcard/myHead/";//sd路径
    private static final int ACTIVITY_RESULT_FOR_UPDATE = 110;
    private int img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        initData();
        initView();
    }

    @Override
    protected void initData() {
        tv_top_title.setText("个人资料");
    }

    @Override
    protected void initView() {
        String phone = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.MOBILEPHONE, "");
        if(!phone.equals("")){
            if (phone.length()>9){
                StringBuilder builder=new StringBuilder(phone);
                builder.replace(3,7,"****");
                tv_nick.setText(builder.toString());
            }
        }
    }
    @Event(value = {R.id.imgbtn_left,R.id.rl_head}, type = View.OnClickListener.class)
    private void getEvent(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.imgbtn_left:
                finish();
                break;
            case R.id.rl_head:
//                showpopmwnu();
                break;
            default:break;

        }
    }
    private void showpopmwnu() {

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //ActivityCompat.requestPermissions(AdminAccountActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CONTEXT_INCLUDE_CODE);
                return;
            } else {
                Intent selectPhotoIntent = new Intent(this, SelectPhotoActivity.class);
                startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
            }
        } else {
            Intent selectPhotoIntent = new Intent(this, SelectPhotoActivity.class);
            startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case ACTIVITY_RESULT_FOR_UPDATE:
                if (resultCode == RESULT_OK) {
                    String head1 = data.getStringExtra("head");
                    String from = data.getExtras().getString("from");

                    if ("1".equals(from)) {
                        Map<String, Object> map = new HashMap<>();
                        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
                        map.put("userId", userid);
                        if(img==2){
                            map.put("avatar",new File(headPath)+"");
                        }
                        upUserData(map);
                        headPath = "file://" + head1;
                        headPath = head1;
                        Bitmap bt = BitmapFactory.decodeFile(headPath);//从Sd中找头像，转换成Bitmap
                        if (bt != null) {
                            x.image().bind(head_image, headPath);
                        }
                    } else {
                        File temp = new File(Environment.getExternalStorageDirectory()
                                + "/head.jpg");
                        cropPhoto(Uri.fromFile(temp));
                    }
                }

                break;

            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head_btm = extras.getParcelable("data");
                    if (head_btm != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head_btm);//保存在SD卡中
                        head_image.setImageBitmap(head_btm);
                    }
                }
                break;

            default:
                break;
        }
    }
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        headPath = path + "head.jpg";//图片名字
        //    x.image().bind(iv_amend, "file:\\"+headPath);
        try {
            b = new FileOutputStream(headPath);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
        map.put("userId", userid);
        if(img==2){
            map.put("avatar",new File(headPath)+"");
        }
        upUserData(map);
    }
    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }
    private void upUserData(Map<String,Object> map) {
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("--个人资料修改参数--" + key, "" + value + "\n");
            }
        }
        showDialog();
        XUtil.Post(URLConstant.MY_HEAD, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==个人资料修改", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if (res.equals("1")) {
                        CusToast.showToast("修改成功");
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });
    }
}
